package com.dankegongyu.component.jsbridge;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.dankegongyu.component.jsbridge.config.DKWebConfig;
import com.dankegongyu.component.jsbridge.jsbridge.BridgeHandler;
import com.dankegongyu.component.jsbridge.jsbridge.BridgeWebView;
import com.dankegongyu.component.jsbridge.jsbridge.CallBackFunction;
import com.dankegongyu.component.jsbridge.listener.DKWebChromeClientCallback;
import com.dankegongyu.component.jsbridge.listener.DKWebJsPlugin;
import com.dankegongyu.component.jsbridge.listener.DKWebViewClientCallback;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebSettings;

/**
 * 基于腾讯X5内核
 */
public class DKWebView extends BridgeWebView {

    public DKWebView(Context context) {
        this(context, null);
    }

    public DKWebView(Context context, AttributeSet attributeSet) {
        this(context, attributeSet, 0);
    }

    public DKWebView(Context context, AttributeSet attributeSet, int defStyleAttr) {
        super(context, attributeSet, defStyleAttr);
    }

    public void initSettings(DKWebConfig config) {

        WebSettings webSetting = this.getSettings();

        // 设置可以支持缩放
        webSetting.setSupportZoom(config.isSupportZoom());
        // 设置出现缩放工具
        webSetting.setBuiltInZoomControls(config.isUseWideViewPort());
        // 自适应屏幕
        webSetting.setUseWideViewPort(config.isUseWideViewPort());
        webSetting.setLoadWithOverviewMode(config.isLoadWithOverviewMode());
        // 支持通过JS打开新窗口
        webSetting.setJavaScriptCanOpenWindowsAutomatically(config.isJavaScriptCanOpenWindowsAutomatically());
        // 不进行缓存，总是使用网络数据
        // webSetting.setCacheMode(webSetting.LOAD_NO_CACHE);
        // 允许跨域，http://blog.csdn.net/zhangcanyan/article/details/51930775
        webSetting.setAllowFileAccess(config.isAllowFileAccess());
        // 现在遇到个问题：我要报销h5页面里有选图组件，但是显示不出来
        // 看log是因为localStorage访问失败，打开下边这三个就可以了
        webSetting.setAppCacheEnabled(config.isAppCacheEnabled());
        webSetting.setDatabaseEnabled(config.isDatabaseEnabled());
        webSetting.setDomStorageEnabled(config.isDomStorageEnabled());
        webSetting.setGeolocationEnabled(config.isGeolocationEnabled());
        // webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        if (!config.isCacheMode()) {
            webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        }

        webSetting.setAllowContentAccess(config.isAllowContentAccess());
        webSetting.setSavePassword(config.isSavePassword());
        webSetting.setSaveFormData(config.isSaveFormData());

        // 设置UserAgent
        String ua = webSetting.getUserAgentString();
        if (!TextUtils.isEmpty(config.getUserAgent())) {
            if (config.isUserAgentAppend()) {
                webSetting.setUserAgentString(ua + config.getUserAgent());
            } else {
                webSetting.setUserAgentString(config.getUserAgent());
            }
        }

        // webView加载监听事件
        DKWebChromeClientCallback chrome = config.getChromeCallback();
        if (chrome != null) {
            setWebChromeClient(chrome);
        }

        // 对网页中超链接的响应
        DKWebViewClientCallback client = config.getClientCallback();
        setWebViewClient(generateBridgeWebViewClient(client));

        // 下载回调
        if (config.getDownloadListener() != null) {
            setDownloadListener(new DownloadListener() {
                @Override
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                    config.getDownloadListener().onDownload(url, userAgent, contentDisposition, mimeType, contentLength);
                }
            });
        }

        // 设置native与JS交互接口 设置JS支持
        if (config.isJsEnabled()) {
            webSetting.setJavaScriptEnabled(config.isJsEnabled());
            // if (!TextUtils.isEmpty(config.getJsName()) && config.getJsInterface() != null) {
            //     addJavascriptInterface(config.getJsInterface(), config.getJsName());
            // }
            registerJsPlugin(config);
        }


    }

    private void registerJsPlugin(DKWebConfig config) {
        for (final DKWebJsPlugin plugin : config.getJsPlugins()) {
            registerHandler(plugin.getActions(), new BridgeHandler() {
                @Override
                public void handler(String action, String data, CallBackFunction function) {
                    plugin.excute(action, data, function);
                }
            });
        }
    }

}
